from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.conf import settings

from .models import image
import os


# Create your views here.

@csrf_exempt
def showImg(request):
    imgs = image.objects.all()
    content = {
        'imgs': imgs
    }
    for i in imgs:
        print(i.img.url)
    return render(request, 'images/showimg.html', content)


@csrf_exempt
def uploadImg(request):

    if request.method == 'POST':
        new_img = image(
            img=request.FILES.get('img'),
            name=request.FILES.get('img').name
        )
        new_img.save()
    imgs = image.objects.all()
    content = {
        'imgs': imgs
    }
    return render(request, 'images/list_images.html', content)


@csrf_exempt
def del_image(request):
    image_id = request.POST['image_id']
    try:
        img = image.objects.get(id=image_id)
        img_path = settings.BASE_DIR.replace("\\", '/') + img.img.url
        img.delete()
   
        if os.path.exists(img_path):
            try:
                os.remove(img_path)
            except OSError as e:
                print(e)
            else:
                print("File is deleted successfully")
            return JsonResponse({"status": "1"})
        else:
            return JsonResponse({'status': "2"})
    except:
        return JsonResponse({'status': "2"})


def falls_images(request):
    images = image.objects.all()
    return render(request, 'images/fall_images.html', {"images": images})


@csrf_exempt
def edit_image(request):
    image_id = request.POST['image_id']
    img = image.objects.get(id=image_id)
    img_name = img.name.split(".")[0]
    imgs_name = {"background": img_name+'.jpg', "mask": img_name+'.png'}
    img_path = settings.BASE_DIR.replace('\\', '/') + img.img.url
    
    return JsonResponse({'status': "1", 'img_path': img_path, 'imgs_name': imgs_name}) 

    



